package com.my.goodsmanage.service.impl;

import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.my.goodsmanage.dao.PictureMapper;
import com.my.goodsmanage.dao.UserMapper;
import com.my.goodsmanage.entity.Picture;
import com.my.goodsmanage.entity.PictureDto;
import com.my.goodsmanage.service.PictureService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 徐佳辉
 * @date 2020/9/25 19:54
 */
@Service
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture> implements PictureService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PictureMapper pictureMapper;

    @Override
    public boolean uploadPicture(String fileName, Integer goodId, Integer userId) {

        //todo 原先有要更新

        if (goodId == null || userId == null || StringUtils.isEmpty(fileName)) {
            return false;
        }
        QueryWrapper<Picture> wrapper = new QueryWrapper<>();
        wrapper.eq("good_id", goodId);
        Picture picture = pictureMapper.selectOne(wrapper);
        if (picture != null) {
            picture.setAddress("/imgs/" + fileName);
            picture.setTime(new Date());
            int update = pictureMapper.update(picture, wrapper);
            return update > 0;
        }

        Picture p = new Picture();
        p.setUserId(userId);
        p.setGoodId(goodId);
        p.setTime(new Date());
        p.setAddress("/imgs/" + fileName);

        int insert = pictureMapper.insert(p);
        return insert > 0;
    }

    @Override
    public List<PictureDto> pageListCondition(Page<PictureDto> picsPage, int userId, String name) {

        if (userId < 0) {
            return null;
        }
        List<PictureDto> pictureDtos = userMapper.selectAllByUserIdOrName(picsPage, userId, name);
        for (PictureDto pictureDto : pictureDtos) {
            if (pictureDto.getAddress() == null) {
                pictureDto.setAddress("../img/1111.jpg");
            }
            if (pictureDto.getTime() == null) {
                pictureDto.setTime(new Date());
            }
        }
        return pictureDtos;
    }


}
